package com.alibaba.csp.sentinel.dashboard.rule.nacos.flow;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.AbstractRuleNacosProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelNacosConstants;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author marcher
 */
@Component("flowRuleNacosProvider")
public class FlowRuleNacosProvider extends AbstractRuleNacosProvider<List<FlowRuleEntity>> {

    /**
     * 获取规则
     *
     * @param appName   appName
     * @param ip        ip
     * @param port      port
     * @return
     * @throws Exception
     */
    @Override
    public List<FlowRuleEntity> getRules(String appName, String ip, Integer port) throws Exception {
        List<FlowRule> rules = getOriginRules(appName, FlowRule.class);
        if (CollectionUtils.isEmpty(rules)) {
            return new ArrayList<>();
        }

        return rules.stream().map(rule -> FlowRuleEntity.fromFlowRule(appName, ip, port, rule)).collect(Collectors.toList());
    }

    @Override
    public String postfix() {
        return SentinelNacosConstants.FLOW_DATA_ID_POSTFIX;
    }
}
